package com.stormrage.edu.ctrl.edu;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduChapterServ;
import com.stormrage.edu.serv.edu.EduVideoServ;
import com.stormrage.edu.serv.edu.view.EduChapterVideoServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduChapter;
import com.stormrage.entity.edu.rep.EduVideoRep;
import com.stormrage.entity.edu.req.EduChapterReq;
import com.stormrage.entity.edu.req.EduVideoReq;
import com.stormrage.entity.edu.view.EduChapterVideo;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;

/**
 * @Title: EduChapterCtrl.java
 * @Package com.stormrage.edu.ctrl
 * @Description: 章节 Controller
 * @author www.stormragetech.com
 * @date 2016年4月11日
 * @version V1.0
 */
@Controller
@RequestMapping("/chap")
public class EduChapterCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduChapterCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduChapterServ eduChapterServ;

	@Autowired
	private EduChapterVideoServ eduChapterVideoServ;

	@Autowired
	private EduVideoServ eduVideoServ;

	@RequiresPermissions("chap:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "edu/chap/create";

	}

	@RequiresPermissions("chap:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduChapter entity, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			logger.debug(" CAONIMAA " + entity.toString());

			// ------------------ Ctrl操作 ------------------

			Integer index = eduChapterServ.create(entity);
			errMsg = "提示信息：添加编号为【 " + index + " 】课程成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加课程失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/chap/list";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/chap/list";

	}

	@RequiresPermissions("chap:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduChapter entity = eduChapterServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/chap/edit";

	}

	@RequiresPermissions("chap:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, EduChapter req, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		logger.debug(" edit请求为 " + req.toString());

		try {

			// ------------------ Ctrl操作 ------------------
			eduChapterServ.update(req);
			errMsg = "提示信息：修改编号为【 " + req.getId() + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/chap/list";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/chap/list";

	}

	@RequiresPermissions("chap:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduChapterServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/chap/list";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/chap/list";

	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/list")
	public String list(@CurrentUser ShiroAcct curr, EduChapterReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List 】-【 GET 】- 结束运行 ");
		return "edu/chap/list";
	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduChapterReq req) {

		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduChapterServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	/// -------------------------------------------------- ///
	/// ------------------ 已包含课件列表 ------------------ ///
	/// -------------------------------------------------- ///
	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/list/{id}")
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List Video 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EduVideoRep> array = eduVideoServ.queryRepListById(id);
			if (null != array && array.size() > 0)
				model.addAttribute("data", array);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List Video 】-【 GET 】- 结束运行 ");
		return "edu/chap/video/list";
	}

	@RequiresPermissions("chap:del")
	@RequestMapping(value = "/video/del/{cid}/{id}")
	public String deleteView(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 DeleteView 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduChapterVideoServ.deleteById(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的章节课件关联成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除【 " + id + " 】的章节课件关联失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/chap/list/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 DeleteView 】-【 GET 】- 结束运行 ");
		return "redirect:/chap/list/{cid}";

	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/video/add/{id}")
	public String list(@CurrentUser ShiroAcct curr, EduVideoReq req, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List Chap Except 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);
			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 List Chap Except 】-【 GET 】- 结束运行 ");
		return "edu/chap/video/add";

	}

	@RequiresPermissions("chap:view")
	@RequestMapping(value = "/video/ajax/{id}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			EduVideoReq req) {

		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax Chap 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduVideoServ.queryList(id, req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduChapterCtrl 】- 【 Ajax Chap 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("chap:edit")
	@RequestMapping(value = "/video/add/{cid}/{id}")
	public String add(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid, @PathVariable("id") Integer id,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Add 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			EduChapterVideo entity = EduChapterVideo.instance(cid, id);
			eduChapterVideoServ.create(entity);

			errMsg = "提示信息：编号为【 " + cid + " 】的章节关联编号为【 " + id + " 】的课件成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：编号为【 " + cid + " 】的章节关联编号为【 " + id + " 】的课件失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/chap/video/add/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduChapterCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "redirect:/chap/video/add/{cid}";

	}

}
